//
//  DataModel.m
//  TuYouAPP
//
//  Created by L on 14-2-21.
//
//

#import "DataModel.h"
#import <AVOSCloud/AVOSCloud.h>
#import "Util.h"
#import "QiniuSimpleUploader.h"
#import "JSONKit.h"

@implementation testData



@end
@implementation DataModel

@end
@implementation Citys



@end

@implementation TYAd

+(void)getTYAD:( void(^)(TYAd* oneAD,NSString* err) )callback
{
    
    AVQuery *query = [AVQuery queryWithClassName:@"ty_ad"];
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        if( object )
        {
            callback( [[TYAd alloc] initWithAV:object],nil);
        }
        else
        {
            callback(nil,[Util convertAVErr:error]);
        }

    }];
    
//    [[AVQuery queryWithClassName:@"ty_ad"] getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
//        if( object )
//        {
//            callback( [[TYAd alloc] initWithAV:object],nil);
//        }
//        else
//        {
//            callback(nil,[Util convertAVErr:error]);
//        }
//        
//    }];
//
//    
}

-(id)initWithAV:(AVObject *)av
{
    self = [super init];
    if( self )
    {
        self.mimgURL = [av objectForKey:@"imgURL"];
    }
    return self;
}

@end
@implementation TYVersion

+(void)getNewVersion:(void(^)(BOOL have,NSString *url,NSString *versionNum,NSString *Desc,NSString *error))callback
{
   // AVObject *obj = [AVObject objectWithClassName:@"ty_version"];
    
    AVQuery *query = [AVQuery queryWithClassName:@"ty_version"];
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        if (object) {
            callback([object[@"haveNew"]boolValue],object[@"newVersionAddress"],object[@"newVersionNum"],object[@"newVersionDescription"],nil);
        }
        else
        {
            callback(NO,nil,nil,nil,[Util convertAVErr:error]);
        }
    }];
    
  //  AVQuery *query = [obj]
}

@end

@implementation TYUser
{
    AVObject *_avobj;
    QiniuSimpleUploader* _fileUploader;
    NSArray* _allflagavobj;
}
-(id)initWithAV:(AVObject*)av bouruser:(BOOL)bouruser
{
    self = [super init];
    if( self )
    {
    //    self.avobj = [[AVObject alloc]init];
        _type = bouruser;
       _avobj  = av;
        self.mObjId = av.objectId;
        self.mnowUserpointAddr = [av objectForKey:@"nowuserAddress"];
        self.mUserDisplayName = [av objectForKey:@"userDisplayName"];
        self.mHeadImgURL = [av objectForKey:@"HeadImgURL"];
        self.mUserSign = [av objectForKey:@"userSign"];
        self.mUserPointAddr = [av objectForKey:@"userPointInfo"];
        self.mSex = [[av objectForKey:@"Sex"] intValue];
        self.mDuijiang = [av objectForKey:@"userDuijiang"];
        self.mAge =  [NSString stringWithFormat:@"%d", [[av objectForKey:@"userAge"]integerValue ]];
 
     
    }
    return self;
}
//这个需要返回我回复过的动态,包括最新的一条回复
-(void)getMyCommentNewState:(int)page AnyCall:(void(^)(NSArray* array,NSString *eror))callback
{
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
          
          [_avobj fetchIfNeededWithKeys:@[@"my_comment_content"]];
          NSArray* all = [_avobj objectForKey:@"my_comment_content"];
//          int i =(page-1)*ONE_PAGE;
//          int j = all1.count-((page-1)*ONE_PAGE)<ONE_PAGE? all1.count-((page-1)*ONE_PAGE):ONE_PAGE;
//          NSArray *all = [all1 objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(i,j)]];
          if( all )
          {
              AVQuery* query = [AVQuery queryWithClassName:@"ty_content"];
              [query includeKey:@"usertag_pointer"];
              [query includeKey:@"usertag_weibo_pointer"];
              [query whereKey:@"objectId" containedIn:all];
              NSArray* allobj = [query findObjects];
              if( allobj )
              {
                  query = [AVQuery queryWithClassName:@"ty_comment"];
                  [query whereKey:@"content_ojid" containedIn:all];
                  [query whereKey:@"theuser" equalTo:_avobj];
                  [query orderByDescending:@"updatedAt"];
                  [query includeKey:@"theuser"];

                  NSArray* tcomment = [query findObjects];
                  
                  NSMutableDictionary* dic = [[NSMutableDictionary alloc] init]
                  ;
                  
                  for (AVObject* tcav in tcomment ) {
                      TYCommment* tc = [[TYCommment alloc] initWithAV:tcav];
                      NSString* k = [tcav objectForKey:@"content_ojid"];
                      if ( k  &&![dic objectForKey:k])
                          [dic setObject:tc forKey:k];
                  }
                  
                  NSMutableArray* t = [[NSMutableArray alloc] init];
                  for ( AVObject* one in allobj ) {
                      TYUserState* a = [[TYUserState alloc] initWithAV:one];
                      a.mNewestComment= [dic objectForKey:one.objectId];
                      if( a.mNewestComment )
                          [t addObject: a];
                  }
                  
                  [t sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                      
                      TYUserState* c1,*c2;
                      c1 = obj1;
                      c2 = obj2;
                      NSComparisonResult t =  [c1.mNewestComment.mTimeC compare:c2.mNewestComment.mTimeC];
                      
                      if( t == NSOrderedAscending) return NSOrderedDescending;
                      else
                      if( t == NSOrderedDescending) return NSOrderedAscending;
                      else return t;
                  }];
                  
                  dispatch_async(dispatch_get_main_queue(), ^{
                      callback(t,nil);
                  });
                  return ;
              }
           
          }
          dispatch_async(dispatch_get_main_queue(), ^{
              callback(nil,@"暂无数据");
          });
          
      });
}
-(void)getReplyMeCount:(void(^)(int count ,NSString *error))callback
{
    AVQuery *query = [AVQuery queryWithClassName:@"ty_comment"];
    [query whereKey:@"ty_content_UserId" equalTo:[TYUser currentUser].mObjId];
    
    [query countObjectsInBackgroundWithBlock:^(NSInteger number, NSError *error) {
        if (!error) {
              callback(number,nil);
        }
        else
        {
        callback(0,[Util convertAVErr:error]);
            
        }
    }];
}
-(void)getReplyMepage:(int)apge call:(void(^)(NSArray * arr,NSString *error))callback;
{
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
          AVQuery *query = [AVQuery queryWithClassName:@"ty_comment"];
          query.limit = ONE_PAGE;
          query.skip = (apge-1)*ONE_PAGE;
          [query includeKey:@"theuser"];
       //   [query includeKey:@"usertag_pointer"];
          [query whereKey:@"ty_content_UserId" equalTo:[TYUser currentUser].mObjId];
          NSError* error = nil;

          NSArray *objects = [query findObjects:&error];

          if( objects )
          {
              NSMutableArray* arr = [[NSMutableArray alloc] init];
              NSMutableDictionary  * t = [[NSMutableDictionary alloc] init];
            
              for ( AVObject* one in objects ) {

                  TYCommment* thecommmit  = [[TYCommment alloc]initWithAV:one];
                  [arr addObject:thecommmit];
                  NSString *contentId = [one objectForKey:@"content_ojid"];
                  if( [t objectForKey:contentId] )
                  {
                      thecommmit.mWhichIComent = [t objectForKey:contentId];
                      continue;
                  }
                  
                  query = [AVQuery queryWithClassName:@"ty_content"];
                  [query includeKey:@"usertag_pointer"];
                  [query includeKey:@"usertag_weibo_pointer"];

                  [query whereKey:@"objectId" equalTo:contentId];
                  AVObject *thecontent = [query getFirstObject];
                  if ( thecontent ) {
                      
                      TYUserState *aUser =[[TYUserState alloc]initWithAV:thecontent];
                      thecommmit.mWhichIComent = aUser;
                      [t setObject:aUser forKey:contentId];
                  }
                  else
                  {
                      [arr removeObject:thecommmit];
                  }
              }
              
              [t removeAllObjects];
              dispatch_async(dispatch_get_main_queue(), ^{
                  callback(arr,nil);
              });
              
          }
          else
          {
              dispatch_async(dispatch_get_main_queue(), ^{
                  callback(nil,[Util convertAVErr:error]);
              });
          }

    
});


}
-(void)getMyCommentCount:(void(^)(int c))callback
{
    [_avobj fetchInBackgroundWithKeys:@[@"my_comment_content"] block:^(AVObject *object, NSError *error) {
        
        NSArray* a = [object objectForKey:@"my_comment_content"];
        callback( a.count );
        
    }];

}
-(void)getMyPublishCount:(void(^)(int c ))callback
{
    AVQuery *query = [AVQuery queryWithClassName:@"ty_content"];
    if( _type )
        [query whereKey:@"usertag_pointer" equalTo:_avobj];
    else
        [query whereKey:@"usertag_weibo_pointer" equalTo:_avobj];
    [query countObjectsInBackgroundWithBlock:^(NSInteger number, NSError *error) {
        
        callback(number);
        
    }];
}


-(void)modifyUserinfoSex:(NSString *)sex headImage:(UIImage *)headrImage name:(NSString *)name addr:(NSString *)addr sign:(NSString *)sigin age:(int)age duijiang:(NSString *)duijiang callback:(void(^)(NSString *eror))callback
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
    AVUser *user = [AVUser currentUser];
    [user setObject:[NSNumber numberWithInt:[sex isEqualToString:@"男"]?2:1] forKey:@"Sex"];
        if( name )
            [user setObject:name forKey:@"userDisplayName"];
        if( addr )
            [user setObject:addr forKey:@"userPointInfo"];
        if( sigin )
            [user setObject:sigin forKey:@"userSign"];
        
            [user setObject:[NSNumber numberWithInt:age] forKey:@"userAge"];
        
        if( duijiang )
        [user setObject:duijiang forKey:@"userDuijiang"];
        
        if(headrImage)
        {
            NSData *imageData = UIImageJPEGRepresentation(headrImage, 1);
            
            NSString* ret = [NSTemporaryDirectory() stringByAppendingString:
                             [NSString stringWithFormat:@"HeadImgURL"]];
            [imageData writeToFile:ret atomically:YES];
            
            NSString* retfilekey = nil;
            _fileUploader = [QiniuSimpleUploader getuploader];
            
            
            retfilekey = [_fileUploader uploadFileSYN:ret key:@"?" extra:nil];
            
            NSDictionary *adic = [retfilekey objectFromJSONString];
            NSString *key = [adic objectForKey:@"key"];
            NSString *headUrl = [Util makeBigImgURL:key];
            
            if (!retfilekey) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    callback(@"修改失败");
                    
                });
            }
            [user setObject:headUrl forKey:@"HeadImgURL"];
        }
    if( [user save] )
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            callback(nil);
            
        });
    }
    else{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            callback(@"修改失败");
            
        });
    }
    });
}
-(void)getMyPublish:(int)page  AnyCall:(void(^)(NSArray* array,NSString *eror))callback
{
 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        AVQuery *query = [AVQuery queryWithClassName:@"ty_content"];
        
        if( _type )
            [query whereKey:@"usertag_pointer" equalTo:_avobj];
        else
            [query whereKey:@"usertag_weibo_pointer" equalTo:_avobj];
        query.limit = ONE_PAGE;
        query.skip = (page-1)*ONE_PAGE;
        [query includeKey:@"usertag_pointer"];
        [query includeKey:@"usertag_weibo_pointer"];
        [query orderByDescending:@"real_order_time"];
            //获取关联到这条线路的节点或者路段的,都算这个线路的,因为一个内容有可能被关联到多个线路,比如 2条线路都进过成都,那么在成都发生的内容就被关联到2个线路,但是,ty_content只记录了一条线路,所有,还需要这么查询,
        //目前不处理.
        //  AVQuery* queryor = [AVQuery queryWithClassName:@"ty_content"];
        //    [queryor whereKey:@"ty_node_ojid" ];
        //    [AVQuery orQueryWithSubqueries:queryor];
        NSError* error = nil;
        NSArray *objects = [query findObjects:&error];
        
        if( objects )
        {
            NSMutableArray* arr = [[NSMutableArray alloc] init];
            
            for ( AVObject* one in objects ) {
                [arr addObject: [[TYUserState alloc] initWithAV:one] ];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(arr,nil);
            });
            
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(nil,[Util convertAVErr:error]);
            });
        }
        
    });

}
-(void)getMyFlag:(void(^)( NSInteger flag ,NSString *eror ))callback
{
    if( _allflagavobj && !_mbchanged )
    {
        NSInteger f = 0;
        for ( AVObject* one in _allflagavobj ) {
            f |= [[one objectForKey:@"flag"] intValue];
        }
        callback(f,nil);
        return;
    }
    
    AVQuery* query = [AVQuery queryWithClassName:@"ty_user_flag"];
    [query whereKey:@"userojid" equalTo:_mObjId];
    [query selectKeys:@[@"flag"]];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if( objects )
        {
            NSInteger f = 0;
            for ( AVObject* one in objects ) {
                f |= [[one objectForKey:@"flag"] intValue];
            }
            _allflagavobj = objects;
            callback(f,nil);
            
        }
        else
        {
            callback(0,[Util convertAVErr:error]);
        }
        _mbchanged = NO;
    }];
}

-(void)clearAllFlags
{
    _mbchanged = YES;
    if( _allflagavobj )
    {
        [AVObject deleteAllInBackground:_allflagavobj block:^(BOOL succeeded, NSError *error) {
        }];
    }
}
-(void)clearFlag:(UserFlag)f
{
    _mbchanged = YES;
    for ( AVObject* one in _allflagavobj ) {
        
        if( [[one objectForKey:@"flag"] intValue] == f )
        {
            [one deleteEventually];
        }
    }
}

-(TYRoad*)whereIat:(int)howLast
{
    if( 0 == howLast )
    {
        
    }
    return nil;
}

-(void)getAllNotDealCount:(void(^)(NSInteger count ,NSString *eror))callback
{
//    if( _allflagavobj && !_mbchanged )
//    {
//        callback( _allflagavobj.count , nil );
//        return;
//    }
    
    AVQuery* query = [AVQuery queryWithClassName:@"ty_user_flag"];
    [query whereKey:@"userojid" equalTo:_mObjId];
    [query selectKeys:@[@"flag"]];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if( objects )
        {
            _allflagavobj = objects;
            callback(objects.count,nil);
        }
        else
        {
            callback(0,[Util convertAVErr:error]);
        }
        _mbchanged = NO;
    }];
}
+(void)updateUser
{
    AVUser *av = [AVUser currentUser];
    [TYUser currentUser].mUserDisplayName = [av objectForKey:@"userDisplayName"];
    [TYUser currentUser].mHeadImgURL = [av objectForKey:@"HeadImgURL"];
    [TYUser currentUser].mSex = [[av objectForKey:@"Sex"] intValue];
    [TYUser currentUser].mUserSign = [av objectForKey:@"userSign"];
    [TYUser currentUser].mUserPointAddr = [av objectForKey:@"userPointInfo"];
    [TYUser currentUser].mAge =  [NSString stringWithFormat:@"%d", [[av objectForKey:@"userAge"]integerValue ]];
    [TYUser currentUser].mDuijiang = [av objectForKey:@"userDuijiang"];
}

+(BOOL)isNeedLogin
{
    AVUser* u = [AVUser currentUser];
    if ( !u )
    {
        return YES;
    }
    
    if( ![u objectForKey:@"userDisplayName"] )
        return YES;
    return NO;
}

+(TYUser *)currentUser
{
    static  TYUser *tyuser=nil;
    if (tyuser) {
        return tyuser;
    }
    @synchronized(tyuser)
    {
  
        if ([AVUser currentUser] == nil) {
            
            return nil;
        }
        
        if( tyuser == nil )
            tyuser = [[TYUser  alloc ]initWithAV:[AVUser currentUser] bouruser:YES];
    }
    return  tyuser;
}
@end

@implementation TYCommment
{
    NSString*   _contentOjid;
    NSString*   _Ojid;
    AVObject*   _whoObj;//这条评论是哪个评论的,
}
-(id)initWithAV:(AVObject *)av username:(NSString*)username
{
    self = [super init];
    if( self )
    {
        self.mUserName = username;
        self.mText = [av objectForKey:@"txt"];
        
        if (av.updatedAt) {
            self.mTimeC = av.updatedAt;
        }
        else
            self.mTimeC = av.createdAt;
        
        self.mTime = [Util FormartTime:_mTimeC bfull:NO];
        
        _Ojid = av.objectId;
        _contentOjid = [av objectForKey:@"content_ojid"];
        _whoObj = ((AVObject*)[av objectForKey:@"theuser"]);
        
        
        AVObject* taguserobj = [av objectForKey:@"taguser_pointer"];
        if( taguserobj )
        {
            self.mTagUserName = [taguserobj objectForKey:@"userDisplayName"];
        }
    }
    return self;
}
-(id)initWithAV:(AVObject *)av
{
    self = [super init];
    if( self )
    {
        self.mUserName = [[av objectForKey:@"theuser"] objectForKey:@"userDisplayName"];
        self.mText = [av objectForKey:@"txt"];
    
        if (av.updatedAt)
            self.mTimeC = av.updatedAt;
        else
            self.mTimeC = av.createdAt;
        
        self.mTime = [Util FormartTime:_mTimeC bfull:NO];

        _Ojid = av.objectId;
        _contentOjid = [av objectForKey:@"content_ojid"];
        _whoObj = ((AVObject*)[av objectForKey:@"theuser"]);
        
        
        
        AVObject* taguserobj = [av objectForKey:@"taguser_pointer"];
        if( taguserobj )
        {
            self.mTagUserName = [taguserobj objectForKey:@"userDisplayName"];
        }
    }
    return self;
}
-(void)reBackThis:(NSString*)txt callback:(void(^)(NSString* err,TYCommment *nowComment))callback
{
    

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        AVUser* user = [AVUser currentUser];
        if( !user )
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(@"请先登陆",nil);
            });
            return ;
        }
        
        AVObject* obj = [AVObject objectWithClassName:@"ty_comment"];
        
        [obj setObject:txt forKey:@"txt"];
        [obj setObject:_Ojid forKey:@"comment_ojid"];//回复的那条评论ID
        [obj setObject:_contentOjid forKey:@"content_ojid"];//评论的动态ID
        [obj setObject:user forKey:@"theuser"];//评论者
        //[obj setObject:_whoOjid forKey:@"taguser_ojid"];//将要回复的这条评论的作者,,优化速度
        [obj setObject:_whoObj forKey:@"taguser_pointer"];
        
        
        [user addUniqueObject:_contentOjid forKey:@"my_comment_content"];
        
        NSError* err;
        if( ![obj save:&err] )
        {
            [obj delete];
            dispatch_async(dispatch_get_main_queue(), ^{
                callback( [Util convertAVErr:err], nil);
            });
        }
        else
        {
            [self.mWhichIComent addCommentCount];
            NSString* username = [user objectForKey:@"userDisplayName"];
            dispatch_async(dispatch_get_main_queue(), ^{
                callback( nil,[[TYCommment alloc]initWithAV:obj username:username] );
            });
            
            if( _whoObj.objectId && ![_whoObj.objectId isEqualToString: user.objectId] )
            {
                NSString* pushText = [NSString stringWithFormat:@"@%@ 回复了你:%@",username,txt];
                [TYUtil sendItPush:E_ReBackMe  txt:pushText userOjid:_whoObj.objectId];
            }
            
        }
        [user saveInBackground];
       
    });
}
@end

@implementation TYUserState
{
    AVObject*   _theav;
}

+(void)getOneStatus:(NSString*)objid callback:(void(^)(TYUserState* one, NSString* err))callback
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        AVQuery* query = [AVQuery queryWithClassName:@"ty_content"];
    
        [query includeKey:@"usertag_weibo_pointer"];
        [query includeKey:@"usertag_pointer"];
        [query whereKey:@"objectId" equalTo:objid];
        AVObject* obj = [query getFirstObject];
        if ( obj )
        {
            TYUserState* stat = [[TYUserState alloc] initWithAV:obj];
            dispatch_async(dispatch_get_main_queue(), ^{
                callback( stat , nil );
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                callback( nil , @"获取数据失败" );
            });
        }
    });
    
}

+(void)publishState:(CLLocationCoordinate2D)pusblishAtHere pointinfo:(NSString*)pointinfo txt:(NSString*)txt imgArr:(NSArray*)imgArr callback:(void(^)(NSString* erra,NSString*objid))call
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSLog(@"pub start times");
        AVUser* nowuser = [AVUser currentUser];
        if( nowuser == nil )
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                call(@"请先登陆",nil);
            });
            
            return;
        }
        
        AVObject* obj = [AVObject objectWithClassName:@"ty_content"];
        if( txt )
            [obj setObject:txt forKey:@"text"];
        if( imgArr )
            [obj addObjectsFromArray:imgArr forKey:@"img_files"];
        
        if( pusblishAtHere.latitude != 0.0f && pusblishAtHere.longitude != 0.0f)
        {
            AVGeoPoint* nowpoint = [AVGeoPoint geoPointWithLatitude:pusblishAtHere.latitude longitude:pusblishAtHere.longitude];
        
            [obj setObject:nowpoint forKey:@"gePoint"];
        }
        
        [obj setObject:[NSNumber numberWithInt:1] forKey:@"content_type"];//自己的数据
        //[obj setObject:nowuser.objectId forKey:@"usertag_ojid"];//由于查询速度比较慢,用pointer,,,
        [obj setObject:nowuser forKey:@"usertag_pointer"];
        
        [obj setObject:pointinfo forKey:@"pointInfo"];
        [obj setObject:[NSNumber numberWithInt:0] forKey:@"auth_state"];//默认审核通过
        
        
        //关联节点
        TYNode* rel_node = [TYNode getNearNode:pusblishAtHere];
        TYRoad* rel_road = nil;
        if( rel_node )
        {
            [obj setObject:rel_node.mOjid forKey:@"ty_node_ojid"];
            [obj setObject:rel_node.mTheAV forKey:@"ty_node_obj"];
            [obj setObject:rel_node.mName forKey:@"rel_info"];//如果关联到了节点就填入信息,
        }
        
        //关联路段
        rel_road = [TYRoad getNearRoad:pusblishAtHere];
        if( rel_road )
        {
            [obj setObject:rel_road.mOjid forKey:@"ty_road_ojid"];
            //如果节点有,就不要这个信息,没得才需要路段的名字
            if( rel_node == nil ) [obj setObject:rel_road.mName forKey:@"rel_info"];
        }
        
        //关联线路的线路objid
        TYLine* rel_line = nil;
        if( rel_road )
            rel_line = [TYLine getLineWithRoad:rel_road];
        
        if( rel_line )
        {
            [obj setObject:rel_line.mOjid forKey:@"rel_line_ojid"];
        }
        
        [obj setObject:[NSNumber numberWithInt:E_UnKnow] forKey:@"content_style"];
        [obj setObject:[NSDate date] forKey:@"real_order_time"];//这个是排序用的时间,因为有挖掘的数据,所以不能用updatedAt作为排序字段,
        
        NSError* err;
        if( ![obj save:&err] )
        {//如果发布失败了
            [obj delete];
        }
        else
        {
            if( [obj fetchWithKeys:@[@"updatedAt"] error:nil] )
            {
                [obj setObject:obj.updatedAt forKey:@"real_order_time"];
                [obj save];//为了更新为正确的时间,,这样不保险,有可能没机会执行,,应该是在服务器执行这个事情,以后弄个JS云代码
            }
        }
        NSLog(@"pbu end times");
        
        dispatch_async(dispatch_get_main_queue(), ^{
        
            call([Util convertAVErr:err],obj.objectId);
        
        });
        
    });
}

-(id)initWithAV:(AVObject *)av
{
    self = [super init];
    if( self )
    {
        _theav = av;
        self.objId = av.objectId;
        
        NSString *astr = [av objectForKey:@"text"];
        if (astr) {
            NSMutableString *str = [[NSMutableString alloc]initWithString:astr];
            NSRange   range = [str rangeOfString:@"我在:"];
            if (range.location ==NSNotFound) {
                range = [str rangeOfString:@"我在这里:"];
                if (range.location != NSNotFound) {
                    self.mContext =  [str substringWithRange:NSMakeRange(0, range.location)];
                }
                else
                {
                    self.mContext = str;
                    
                }
            }
            else
            {
                
                    self.mContext =  [str substringWithRange:NSMakeRange(0, range.location)];
               // self.mContext = str;
                
            }
   

        }
        else
        {
            self.mContext = nil;
        }
  
        
     //   self.mContext = ;
        self.mImgArr = [av objectForKey:@"img_files"];
        self.mPointInfo = [av objectForKey:@"pointInfo"];
        self.mRelInfo = [av objectForKey:@"rel_info"];
        self.mStyle = [[av objectForKey:@"content_style"] intValue];
        self.mTimeC = [av objectForKey:@"real_order_time"];
        self.mTimeText =  [Util FormartTime:_mTimeC bfull:NO];
        
        AVGeoPoint* p = [av objectForKey:@"gePoint"];
        int f;
        
        if (p == nil) {
            self.mPBetweenInfo = @"未知坐标";
            
        }
        else if( [GInfo shareClient].mIsVaild )
        {
            double miles = [Util getTwoPointDist:CLLocationCoordinate2DMake(p.latitude, p.longitude) latlngb:[GInfo shareClient].mNowUserPoint posBetween:&f];
            
            NSString* ds;
            NSString*
            bet = [@[@"",@"东北",@"东南",@"西北",@"西南"]  objectAtIndex:f];
            
     
            if( miles < 1000 )
            {
                ds = [NSString stringWithFormat:@"%@%dm",bet,(int)miles];
            }
            else if( miles < 100000 )
            {
                ds = [NSString stringWithFormat:@"%@%.1fkm",bet,miles/1000];
            }
            else
            {
                ds = [NSString stringWithFormat:@"%@%dkm",bet,(int)(miles/1000)];
            }
            self.mPBetweenInfo = ds;
        }
        else
        {
            self.mPBetweenInfo = @"未知坐标";
        }
        self.mReBackCount = [[av objectForKey:@"comment_count"] intValue];
        
        AVObject* taguser = [av objectForKey:@"usertag_pointer"];
        if( taguser )
        {
            self.mTaguser = [[TYUser alloc] initWithAV:taguser bouruser:YES];
        }
        AVObject* taguser_weibo = [av objectForKey:@"usertag_weibo_pointer"];
        if( taguser_weibo )
        {
            self.mTaguser = [[TYUser alloc] initWithAV:taguser_weibo bouruser:NO];
        }
    }
    return self;
}

-(void)addCommentCount
{
    [_theav incrementKey:@"comment_count"];
    [_theav saveInBackground];
}

-(void)getCommentByTime:(NSDate*)theTime bback:(BOOL)bback  callback:(void(^)(NSArray* arr, NSString* err))callback
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        AVQuery* query = [AVQuery queryWithClassName:@"ty_comment"];
        [query whereKey:@"content_ojid" equalTo:_theav.objectId];
        [query orderByDescending:@"updatedAt"];
        query.limit = ONE_PAGE*2;
        
        if( bback )
        {
            if( theTime )
                [query whereKey:@"updatedAt" greaterThan:theTime];
        }
        else
        {
            if( theTime )
                [query whereKey:@"updatedAt" lessThan:theTime];
        }
        
        [query includeKey:@"theuser"];
        [query includeKey:@"taguser_pointer"];
        NSArray* all = [query findObjects];
        NSMutableArray* tmp = [[NSMutableArray alloc] init];
        for(AVObject* one in all )
        {
            TYCommment* tc = [[TYCommment alloc] initWithAV:one];
            tc.mWhichIComent = self;
            [tmp addObject: tc];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            callback(tmp,nil);
        });
        
    });
}
-(void)getComment:(int)page callback:(void(^)(NSArray* arr, NSString* err))callback
{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        if( page < 1 )
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(nil,@"参数错误");
            });
        }
        
        AVQuery* query = [AVQuery queryWithClassName:@"ty_comment"];
        [query whereKey:@"content_ojid" equalTo:_theav.objectId];
        [query orderByDescending:@"updatedAt"];
        query.limit = ONE_PAGE;
        query.skip = (page-1)*ONE_PAGE;
        [query includeKey:@"theuser"];
        [query includeKey:@"taguser_pointer"];
        NSArray* all = [query findObjects];
        NSMutableArray* tmp = [[NSMutableArray alloc] init];
        for(AVObject* one in all )
        {
            TYCommment* tc = [[TYCommment alloc] initWithAV:one];
            tc.mWhichIComent = self;
            [tmp addObject: tc];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            callback(tmp,nil);
        });
        
    });
    
}
-(void)commentThis:(NSString*)txt tagUser:(NSString *)objid coordnate:(CLLocationCoordinate2D)itpoint callback:(void(^)( NSString* err , TYCommment *comment))callback
{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        AVUser*  user = [AVUser currentUser];
        if( !user )
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(@"请先登陆",nil);
            });
        }
        
        AVObject* obj = [AVObject objectWithClassName:@"ty_comment"];
        [obj setObject:txt forKey:@"txt"];
        [obj setObject:user forKey:@"theuser"];
        [obj setObject:_theav.objectId forKey:@"content_ojid"];
        [obj setObject:objid forKey:@"ty_content_UserId"];
       // [obj setObject: forKey:<#(NSString *)#>]
        AVGeoPoint *gep = [AVGeoPoint geoPointWithLatitude:itpoint.latitude longitude:itpoint.longitude];
        [obj setObject:gep forKey:@"coordinate"];
        [user addUniqueObject:_theav.objectId forKey:@"my_comment_content"];
        if( ![obj save] )
        {
            [obj delete];
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(@"评论失败",nil);
            });
        }
        else
        {
            [self addCommentCount];
            NSString* itusername = [user objectForKey:@"userDisplayName"];
            
             if([obj fetchWithKeys:@[@"updatedAt"] error:nil])
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    callback(nil,[[TYCommment alloc]initWithAV:obj username:itusername] );
                });
                
                if( _mTaguser.mObjId && ![_mTaguser.mObjId isEqualToString:user.objectId] )
                {
                    if( _mTaguser.type )
                    {
                        NSString* pushText = [NSString stringWithFormat:@"@%@ 评论了你:%@",itusername,txt];
                        [TYUtil sendItPush:E_ReBackMyStatus txt:pushText userOjid:_mTaguser.mObjId];
                    }
                    else
                    {//否则,可能会通知微博...
                        
                    }
                }
                
            }
             else{
                 callback(@"评论失败",nil );
             }
           
        }
        [user save];
    });
    
    
}
@end

@implementation TYLine
{
    NSString* _toptipStateOjid;
}
-(TYUserState *)getFirstTishi
{
    AVQuery* query = [self makeQueryLineStatus];
    [query whereKey:@"auth_state" equalTo:[NSNumber numberWithInt:0]];
    [query whereKey:@"bNotif" equalTo:[NSNumber numberWithInt:1]];
    [query includeKey:@"usertag_weibo_pointer"];
    [query includeKey:@"usertag_pointer"];
    
//    BOOL border = YES;
//    if( [GInfo shareClient].mIsVaild )
//    {
//        AVGeoPoint* p = [AVGeoPoint geoPointWithLatitude:[GInfo shareClient].mNowUserPoint.latitude longitude:[GInfo shareClient].mNowUserPoint.longitude];
//        [query whereKey:@"gePoint" nearGeoPoint:p];
//        border =NO;//没位置就按照时间
//    }

//    if( border )
        [query orderByDescending:@"real_order_time"];
    
    AVObject *object = [query getFirstObject];
    TYUserState *userStatus = [[TYUserState alloc]initWithAV:object];
    return userStatus;

}
+(void)getAllLines:( void(^)(NSArray* all,NSString* err) )callback;
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        AVQuery* query = [AVQuery queryWithClassName:@"ty_line"];
        [query orderByAscending:@"order_index"];
        NSError* error = nil;
        NSArray*  objects = [query findObjects:&error];
        
        if( !objects )
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(nil, [Util convertAVErr:error] );
            });
        }
        else{
            NSMutableArray* arr = [[NSMutableArray alloc] init];
            for (AVObject* one in objects )
            {
                TYLine* tl = [[TYLine alloc] initWithAV:one];
                
                [tl fetchAllRoad];
                tl.mTopUserStatus = [tl getFirstTishi];
                tl.mSameWayCount = [tl getSameWayCount];
                
                [arr addObject:  tl ];
            }
            [GInfo shareClient].mAllLine = arr;//记录当前所有的线路
            
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(arr,nil);
            });
        }
        
    });
}

+(TYLine*)getLineWithNode:(TYNode*)node
{//这个node有可能是一个小地名,是我们配置的节点的一个下属地方,这样就需要找到父级节点,或者父父级,...
    //还有个办法就是通过,路段来关联,把这个点拿到ty_road_lbs坐标里面找,看哪个最近,就认为是那个路段的,然后就可以根据路段关联到线路了,
    return nil;
    
    //这个接口暂时没地方需要用了,需要的时候根据上面的描述来写
    AVQuery* query = [AVQuery queryWithClassName:@"ty_line"];
    [query whereKey:@"sub_node_lines" containsString:[NSString stringWithFormat:@"N_%@",node.mOjid]];
    AVObject* f = [query getFirstObject];
    TYLine* it = nil;
    if( f )
        it = [[TYLine alloc] initWithAV:f];

    return it;
}

//根据路段来获取线路
+(TYLine*)getLineWithRoad:(TYRoad *)road
{
    AVQuery* query = [AVQuery queryWithClassName:@"ty_line"];
    [query whereKey:@"sub_node_lines" containsString:[NSString stringWithFormat:@"%@",road.mOjid]];
    AVObject* f = [query getFirstObject];
    TYLine* it = nil;
    if( f )
        it = [[TYLine alloc] initWithAV:f];
    
    return it;
}
-(void)getTopState:( void(^)( TYUserState* thetop ,NSString* err) )callback
{
    if ( _toptipStateOjid ) {
        
        AVQuery* query = [AVQuery queryWithClassName:@"ty_content"];
        [query whereKey:@"objectId" equalTo:_toptipStateOjid];
        [query includeKey:@"usertag_weibo_pointer"];
        [query includeKey:@"usertag_pointer"];
        [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            
            if( object )
            {
                TYUserState* t = [[TYUserState alloc] initWithAV:object];
                
                callback(t,nil);
            }
            else
            {
                callback(nil,@"获取置顶动态失败");
            }
            
        }];
        
    }
    
}
-(id)initWithAV:(AVObject *)av
{
    self = [super init];
    if( self )
    {
        self.mLineName = [av objectForKey:@"line_name"];
        self.mLineDesc = [av objectForKey:@"line_desc"];
        self.mBackImgURL = [av objectForKey:@"line_img"];
       // self.mTopTipText = [av objectForKey:@"toptip_desc"];
        self.mOjid = av.objectId;
        _toptipStateOjid = [av objectForKey:@"toptip_ojid"];
        self.mAllSubRoadOjid = [av objectForKey:@"sub_node_lines"];
        self.mAllNodeOjid = [av objectForKey:@"the_nodes"];
    }
    return self;
}

-(NSString*)fetchAllRoad
{
    if( _mAllSubRoadOjid )
    {
        //dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
      
            AVQuery*  query = [AVQuery queryWithClassName:@"ty_road"];
            [query whereKey:@"objectId" containedIn:_mAllSubRoadOjid];
            NSArray *objects = [query findObjects];
            if( objects )
            {
                NSMutableArray* arr = [[NSMutableArray alloc] init];
                NSMutableArray* tarr = [[NSMutableArray alloc] init];
                for ( AVObject* one in objects ) {
                    
                    TYRoad* a = [[TYRoad alloc] initWithAV:one];
                    
                    [arr addObject:a];
                    if( a.mstartNodeOjid && ![tarr containsObject:a.mstartNodeOjid] )
                        [tarr addObject: a.mstartNodeOjid ];
                    
                    if( a.mendNodeOjid && ![tarr containsObject:a.mendNodeOjid] )
                        [tarr addObject: a.mendNodeOjid ];
                    
                }
                
                query = [AVQuery queryWithClassName:@"ty_node"];
                [query selectKeys:@[@"nname",@"cityid",@"node_id"]];//目前只需要这几个数据,根据上面的属性来定,
                
                if( _mAllNodeOjid )//把特殊配置的一起
                    [tarr addObjectsFromArray:_mAllNodeOjid];
                
                [query whereKey:@"objectId" containedIn:tarr];
                
                objects = [query findObjects];
                
                if( !_mAllNodeOjid )
                    self.mAllNodeOjid = [[NSMutableArray alloc] initWithArray:tarr];
                
                self.mAllNodeObj = [[NSMutableArray alloc] init];
                self.mAllNodeIds = [[NSMutableArray alloc] init];
                
                for ( AVObject* onenode in objects ) {
                    for ( TYRoad * r in arr ) {
                        if( [r.mstartNodeOjid isEqualToString:onenode.objectId] )
                        {
                            r.mStartNode = [[TYNode alloc] initWithAV:onenode];
                            [(NSMutableArray*)_mAllNodeObj addObject:r.mStartNode];
                            
                            [(NSMutableArray*)_mAllNodeIds addObject:[NSNumber numberWithInt:r.mStartNode.mNodeId]];
                            
                        }
                        
                        if( [r.mendNodeOjid isEqualToString: onenode.objectId] )
                        {
                            r.mEndNode = [[TYNode alloc] initWithAV:onenode];
                            [(NSMutableArray*)_mAllNodeObj addObject:r.mEndNode];
                            
                            [(NSMutableArray*)_mAllNodeIds addObject:[NSNumber numberWithInt:r.mEndNode.mNodeId]];
                            
                        }
                    }
                }
                
                self.mAllRoadObj = arr;
                /*
                dispatch_async(dispatch_get_main_queue(), ^{
                    callback(arr,nil);
                });
                */
            }
            else
            {
                /*
                dispatch_async(dispatch_get_main_queue(), ^{
                    callback(nil,@"获取路段失败");
                });
                */
                
            }
        //});
    }
    else
    {
        //callback(nil,@"没有路段");
        return @"没有路段";
    }
    return nil;
}
-(AVQuery*)makeQueryLineStatus
{
    if( !_mAllSubRoadOjid || !_mOjid || !_mAllNodeIds || !_mAllSubRoadOjid )
        return nil;
    
    //要包含共有路段,如果这个动态的线路不是目前这个,但是,里面的路段又有这条线路的ID,
    AVQuery* queryWithRoad = [AVQuery queryWithClassName:@"ty_content"];
    [queryWithRoad whereKey:@"ty_road_ojid" containedIn:_mAllSubRoadOjid];
    [queryWithRoad whereKey:@"rel_line_ojid" notEqualTo:_mOjid];
    
    //或者,指定了,就是这个线路的,
    AVQuery* queryWithLine = [AVQuery queryWithClassName:@"ty_content"];
    [queryWithLine whereKey:@"rel_line_ojid" equalTo:_mOjid];
    
    //或者,节点属于这个线路,.但是,线路ID又不是这个线路,也算,.比如,成都,拉萨,这种公共点,318 317线共有
    
    AVQuery* queryWithNode = [AVQuery queryWithClassName:@"ty_content"];
    //[queryWithNode whereKey:@"rel_line_ojid" notEqualTo:_mOjid];
    //[queryWithNode whereKey:@"ty_road_ojid" notContainedIn:_mAllSubRoadOjid];
    //[queryWithNode whereKey:@"ty_node_ojid" containedIn:_mAllNodeOjid];//一样那个问题,小节点问题,
    
    
    AVQuery* querySubNode = [AVQuery queryWithClassName:@"ty_node"];
    [querySubNode whereKey:@"topid" containedIn:_mAllNodeIds];
    [querySubNode whereKey:@"rel_line_ojid" notEqualTo:_mOjid];
    [querySubNode whereKey:@"ty_road_ojid" notContainedIn:_mAllSubRoadOjid];
    
    [queryWithNode whereKey:@"ty_node_obj" matchesQuery:querySubNode];
    
    return [AVQuery orQueryWithSubqueries:@[queryWithRoad,queryWithLine,queryWithNode]];
}

-(int)getSameWayCount
{
    AVQuery* query = [AVQuery queryWithClassName:@"_User"];
    [query whereKey:@"now_rel_line_ojid" equalTo:_mOjid];//所有用户在这个线的人,
    
#ifdef DEBUG
    return arc4random() % 800 ;
#else
    return [query countObjects];
#endif
}
-(void)getBestStatesOfTheLineByTime:(int)page bback:(BOOL)bback callback:( void(^)(NSArray* all,NSString* err) )callback
{
    
    if( page < 1 )
    {
        callback(nil,@"参数错误");
        return;
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        BOOL border = YES;
        AVQuery* query = [self makeQueryLineStatus];
        if( !query )
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(nil,@"获取数据失败");
            });
            return ;
            
        }
        if( [GInfo shareClient].mIsVaild )
        {
            AVGeoPoint* p = [AVGeoPoint geoPointWithLatitude:[GInfo shareClient].mNowUserPoint.latitude longitude:[GInfo shareClient].mNowUserPoint.longitude];
            
            [query whereKey:@"gePoint" nearGeoPoint:p];
            border = NO;//没位置就按照时间
        }
        
        [query whereKey:@"auth_state" equalTo:[NSNumber numberWithInt:0]];
        [query whereKey:@"bBest" equalTo:[NSNumber numberWithInt:1]];
        
        [query includeKey:@"usertag_weibo_pointer"];
        [query includeKey:@"usertag_pointer"];
        query.limit = ONE_PAGE;
        query.skip = (page-1)*ONE_PAGE;
        if( border )
            [query orderByDescending:@"real_order_time"];
        
        NSError* error = nil;
        NSArray *objects = [query findObjects:&error];
        
        if( objects )
        {
            NSMutableArray* arr = [[NSMutableArray alloc] init];
            
            for ( AVObject* one in objects ) {
                [arr addObject: [[TYUserState alloc] initWithAV:one] ];
                
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(arr,nil);
            });
            
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(nil,[Util convertAVErr:error]);
            });
        }
        
    });
}


-(void)getTishiStatesOfTheLineByTime:(int)page bback:(BOOL)bback callback:( void(^)(NSArray* all,NSString* err) )callback
{
    
    if( page < 1 )
    {
        callback(nil,@"参数错误");
        return;
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        AVQuery* query = [self makeQueryLineStatus];
        if( !query )
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(nil,@"获取数据失败");
            });
            return ;
        }
        
//        BOOL border = YES;
//        if( [GInfo shareClient].mIsVaild )
//        {
//            AVGeoPoint* p = [AVGeoPoint geoPointWithLatitude:[GInfo shareClient].mNowUserPoint.latitude longitude:[GInfo shareClient].mNowUserPoint.longitude];
//            
//            [query whereKey:@"gePoint" nearGeoPoint:p];
//            border =NO;//没位置就按照时间
//        }
        
        [query whereKey:@"auth_state" equalTo:[NSNumber numberWithInt:0]];
        [query whereKey:@"bNotif" equalTo:[NSNumber numberWithInt:1]];
        
        [query includeKey:@"usertag_weibo_pointer"];
        [query includeKey:@"usertag_pointer"];
        query.limit = ONE_PAGE;
        query.skip = (page-1)*ONE_PAGE;
//        if( border )
            [query orderByDescending:@"real_order_time"];
        
        NSError* error = nil;
        NSArray *objects = [query findObjects:&error];
        
        if( objects )
        {
            NSMutableArray* arr = [[NSMutableArray alloc] init];
            
            for ( AVObject* one in objects ) {
                [arr addObject: [[TYUserState alloc] initWithAV:one] ];
                
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(arr,nil);
            });
            
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(nil,[Util convertAVErr:error]);
            });
        }
        
    });
}

-(void)getNewestStateOfTheLineByTime:(NSDate*)theTime bback:(BOOL)bback callback:( void(^)(NSArray* all,NSString* err) )callback
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        AVQuery* query = [self makeQueryLineStatus];
        if( !query )
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(nil,@"获取时间失败");
            });
        }
        
        if( bback )
        {
            if( theTime )
                [query whereKey:@"real_order_time" greaterThan:theTime];
        }
        else
        {
            if ( theTime )
                [query whereKey:@"real_order_time" lessThan:theTime];
        }
        
        [query whereKey:@"auth_state" equalTo:[NSNumber numberWithInt:0]];
        
        [query includeKey:@"usertag_weibo_pointer"];
        [query includeKey:@"usertag_pointer"];
        query.limit = ONE_PAGE;
        [query orderByDescending:@"real_order_time"];
        
        NSError* error = nil;
        NSArray *objects = [query findObjects:&error];
        
        if( objects )
        {
            NSMutableArray* arr = [[NSMutableArray alloc] init];
            
            for ( AVObject* one in objects ) {
                [arr addObject: [[TYUserState alloc] initWithAV:one] ];
                
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(arr,nil);
            });
            
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(nil,[Util convertAVErr:error]);
            });
        }
        
    });
    
    
}


@end


@implementation TYNode
-(id)initWithAV:(AVObject *)av
{
    self = [super init];
    if( self && av )
    {
        self.mTheAV = av;
        self.mName = [av objectForKey:@"nname"];
        self.mOjid = av.objectId;
        _mcityid = [[av objectForKey:@"cityid"] intValue];
        _mNodeId = [[av objectForKey:@"node_id"] intValue];
    }
    return self;
}


//直接搜索这个点最近的节点,范围可以控制
+(TYNode*)getNearNode:(CLLocationCoordinate2D)point
{
    AVGeoPoint* p = [AVGeoPoint geoPointWithLatitude:point.latitude longitude:point.longitude];
    AVQuery* query =[AVQuery queryWithClassName:@"ty_node"];
    [query selectKeys:@[@"nname",@"cityid",@"node_id"]];//目前只需要这几个数据,根据上面的属性来定,
    [query whereKey:@"it_gepoint" nearGeoPoint:p withinKilometers:[GInfo shareClient].mRelNodeDistConfig ];
    
    AVObject* obj = [query getFirstObject];//取最近的一个
    if( obj )
    {
        return [[TYNode alloc] initWithAV:obj];
    }
    
    return nil;
}

@end

@implementation TYRoad
-(id)initWithAV:(AVObject *)av
{
    self = [super init];
    if( self && av )
    {
        self.mOjid = av.objectId;
        self.mName = [av objectForKey:@"road_name"];
        self.mstartNodeOjid = [av objectForKey:@"start_node_ojid"];
        self.mendNodeOjid = [av objectForKey:@"end_node_ojid"];
        self.mSpeed = [av objectForKey:@"speed"];
        self.mRoadLevel = [av objectForKey:@"road_level"];
        self.mRoadNO = [av objectForKey:@"road_no"];
        self.mDesc = [av objectForKey:@"road_desc"];
        self.mDist = [av objectForKey:@"road_dist"];
    }
    return self;
}

+(TYRoad*)getNearRoad:(CLLocationCoordinate2D)point
{
    AVGeoPoint* p = [AVGeoPoint geoPointWithLatitude:point.latitude longitude:point.longitude];
    AVQuery* query = [AVQuery queryWithClassName:@"ty_road_lbs"];
    [query whereKey:@"itPoint" nearGeoPoint:p withinKilometers:20];
    AVObject* obj = [query getFirstObject];
    if( obj )
    {
        AVObject* objreoad = [AVQuery getObjectOfClass:@"ty_road" objectId:[obj objectForKey:@"road_ojid"]];
        if( objreoad )
            return  [[TYRoad alloc] initWithAV:objreoad];
    }
    return nil;
}

@end

@implementation TYUtil

+(void)dealBadge
{
    AVInstallation *currentInstallation = [AVInstallation currentInstallation];
    if( currentInstallation )
    {
        [currentInstallation fetchInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            AVInstallation* ttt = (AVInstallation*)object;
            if( ttt.badge )
            {
                [ttt incrementKey:@"badge" byAmount:[NSNumber numberWithInt:-1]];
                
                [ttt saveEventually];
                
                [[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
                [[UIApplication sharedApplication] cancelAllLocalNotifications];
                
            }
        }];
    }
}

+(void)updateUserPoint
{
    [AVGeoPoint geoPointForCurrentLocationInBackground:^(AVGeoPoint *geoPoint, NSError *error) {
        
#if TARGET_IPHONE_SIMULATOR
        
        
        [GInfo shareClient].mNowUserPoint = CLLocationCoordinate2DMake(  30.673811237, 104.06147574);
        [GInfo shareClient].mIsVaild = YES;
        geoPoint = [AVGeoPoint geoPointWithLatitude:30.673811237 longitude:104.06147574];
#else
        
        __block CLLocationCoordinate2D coor ;
        coor.latitude = geoPoint.latitude;
        coor.longitude = geoPoint.longitude;
        if( geoPoint )
        {
            [GInfo shareClient].mNowUserPoint = CLLocationCoordinate2DMake( geoPoint.latitude, geoPoint.longitude);
            [GInfo shareClient].mIsVaild = YES;
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:[Util convertAVErr:error]];
        }
#endif
        if( [GInfo shareClient].mIsVaild )
        {
            AVUser* uuu = [AVUser currentUser];
            if( uuu )
                [[GInfo shareClient]updateUserAddr:geoPoint];
        }
    }];
}


/*
 系统通知：
 
 1、所发布的内容被评论：
 @某某某 评论了你：啦啦啦啦。。。。。
 
 2、所发布的回复被回复：
 @某某某 回复了你：拉风的拉风大
 
 3、系统通知：
 途友通知：奥斯卡房间拉丁方
 
 4、有新的提示：
 途友提示 @某某某 说：通麦大桥中断，预计12小时后方可通行。
 */

+(void)sendItPush:(GotoPage)go txt:(NSString*)txt userOjid:(NSString*)userOjid
{
    NSDictionary* dat = [NSDictionary dictionaryWithObjectsAndKeys:
                         txt, @"alert",
                         @"Increment", @"badge",
                         @"Voicemail.caf", @"sound",
                         [NSNumber numberWithInt:go],@"Ntype",
                         nil];

    AVQuery *pushQuery = [AVInstallation query];
    [pushQuery whereKey:@"userojid" equalTo:userOjid];
    
    AVPush*     push = [[AVPush alloc] init];
    [push setQuery:pushQuery];
    [push setData:dat];
    [push sendPushInBackground];
    
    [TYUtil markUserStatus:userOjid flag:go ];
    
}
+(void)markUserStatus:(NSString*)userOjid  flag:(NSInteger)flag
{
    AVObject* obj = [AVObject objectWithClassName:@"ty_user_flag"];
    [obj setObject:[NSNumber numberWithInt:flag] forKey:@"flag"];
    [obj setObject:userOjid forKey:@"userojid"];
    [obj saveEventually];
}

@end
//全局用户信息,
@implementation GInfo

+(GInfo*)shareClient
{
    static GInfo* g_inst = nil;
    
    if( g_inst == nil )
    {
        @synchronized(g_inst)
        {
            if( g_inst == nil )
            {
                g_inst = [[GInfo alloc] init];
                g_inst.mRelNodeDistConfig = 40;//默认是40KM就认为在这个节点里面
                //这个配置要从网络获取
            }
        }
    }
    return g_inst;
}
-(void)updateUserAddr:(AVGeoPoint*) coordinate
{
     self.search = [[AMapSearchAPI alloc] initWithSearchKey:MapAPIKey Delegate:self];
    AMapReGeocodeSearchRequest *regeoRequest = [[AMapReGeocodeSearchRequest alloc] init];
    regeoRequest.searchType = AMapSearchType_ReGeocode;
    regeoRequest.location = [AMapGeoPoint  locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    regeoRequest.radius = 10000;
    regeoRequest.requireExtension = NO;
    [self.search AMapReGoecodeSearch: regeoRequest];
}
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    NSString *result = [NSString stringWithFormat:@"%@", response.regeocode.formattedAddress];
    NSLog(@"省%@,市%@,区%@",response.regeocode.addressComponent.province,response.regeocode.addressComponent.city,response.regeocode.addressComponent.district);

    __block AVUser* uuu = [AVUser currentUser];
    if( uuu )
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            AVGeoPoint *geopoint = [AVGeoPoint geoPointWithLatitude:request.location.latitude longitude:request.location.longitude];
             
            AVObject* userhi = [AVObject objectWithClassName:@"ty_user_history"];
            [uuu setObject:geopoint forKey:@"nowPoint"];
            [userhi setObject:geopoint forKey:@"nowPoint"];
            [uuu setObject:result forKey:@"nowuserAddress"];
            [userhi setObject:result forKey:@"nowuserAddress"];
            CLLocationCoordinate2D ll = CLLocationCoordinate2DMake(geopoint.latitude, geopoint.longitude);
            
            TYUser* tyuuu = [TYUser currentUser];
            
            
            TYNode* n = [TYNode getNearNode:ll];
            TYRoad* r = [TYRoad getNearRoad:ll];
            if( r )
            {
                [uuu setObject:r.mOjid forKey:@"now_rel_road_ojid"];
                [uuu setObject:r.mName forKey:@"now_rel_road_name"];
          
                [userhi setObject:r.mOjid forKey:@"now_rel_road_ojid"];
                [userhi setObject:r.mName forKey:@"now_rel_road_name"];
                
                TYLine* l = [TYLine getLineWithRoad:r];
                if( l )
                {
                    [uuu setObject:l.mOjid forKey:@"now_rel_line_ojid"];
                    [uuu setObject:l.mLineName forKey:@"now_rel_line_name"];
                    [userhi setObject:l.mOjid forKey:@"now_rel_line_ojid"];
                    [userhi setObject:l.mLineName forKey:@"now_rel_line_name"];
                }
                tyuuu.mNowIAtLine = l;
            }
            if( n )
            {
                [uuu setObject:n.mOjid forKey:@"now_rel_node_ojid"];
                [uuu setObject:n.mName forKey:@"now_rel_node_name"];
                
                [userhi setObject:n.mOjid forKey:@"now_rel_node_ojid"];
                [userhi setObject:n.mName forKey:@"now_rel_node_name"];
                
            }
            
            tyuuu.mNowIAtRoad = r;
            tyuuu.mNowIAtNode = n;
            
            
            [uuu save];
            [userhi setObject:uuu forKey:@"who"];

            [userhi save];
        });
        
        
    }

    
    //  NSLog(@"ReGeo: %@", result);
    
}
@end






